<script setup lang="ts">
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { registerRules } from "../utils/rule";
import type { FormInstance } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { useUserStoreHook } from "@/store/modules/user";
import { useRouter } from "vue-router";
import { initRouter, getTopMenu } from "@/router/utils";
import type {
  RegisterRequest,
  PartialAuthData,
  LoginSuccessData
} from "@/api/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Iphone from "~icons/ep/iphone";
import Keyhole from "~icons/ri/shield-keyhole-line";
import Lock from "~icons/ri/lock-fill";
import Key from "~icons/ri/key-2-line";

const userStore = useUserStoreHook();
const router = useRouter();
const loading = ref(false);
const agree = ref(false);

const agreementLink = "《用户服务协议》";

const form = reactive({
  phone: "",
  verifyCode: "",
  password: "",
  confirmPassword: "",
  inviteCode: ""
});

const formRef = ref<FormInstance>();
const rules = registerRules(form);
const { isDisabled, text, start, end } = useVerifyCode({
  scene: "register",
  resolvePhone: () => form.phone
});

const resetForm = () => {
  end();
  form.phone = "";
  form.verifyCode = "";
  form.password = "";
  form.confirmPassword = "";
  form.inviteCode = "";
};

const handlePartial = (partial: PartialAuthData) => {
  userStore.SET_CURRENTPAGE(0);
  if (partial.incompleteAction === "need_bind_phone") {
    router.replace("/welcome/bindphone");
  } else if (partial.incompleteAction === "need_verify_identity") {
    router.replace("/welcome/verification");
  }
};

const handleSuccess = async () => {
  await initRouter();
  await router.push(getTopMenu(true).path);
  message("注册成功", { type: "success" });
  userStore.SET_CURRENTPAGE(0);
};

const onSubmit = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;
  if (!agree.value) {
    message("请先阅读并同意服务条款", { type: "warning" });
    return;
  }
  loading.value = true;
  try {
    const payload: RegisterRequest = {
      phone: form.phone,
      code: form.verifyCode,
      password: form.password,
      invite_code: form.inviteCode
    };
    const res = await userStore.registerAccount(payload);
    if (res.success && res.data) {
      const data = res.data as PartialAuthData | LoginSuccessData;
      if ((data as PartialAuthData).partial) {
        handlePartial(data as PartialAuthData);
      } else {
        await handleSuccess();
      }
      resetForm();
    } else {
      message(res.msg || "注册失败", { type: "error" });
    }
  } catch (error: any) {
    message(error?.message ?? "注册失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

const onBack = () => {
  end();
  userStore.SET_CURRENTPAGE(0);
};

const sendCode = async () => {
  if (isDisabled.value) return;
  await start(formRef.value, "phone", 60);
};
</script>

<template>
  <el-form ref="formRef" :model="form" :rules="rules" size="large">
    <Motion>
      <el-form-item prop="phone">
        <el-input
          v-model="form.phone"
          clearable
          placeholder="请输入手机号"
          :prefix-icon="useRenderIcon(Iphone)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="80">
      <el-form-item prop="verifyCode">
        <div class="w-full flex justify-between">
          <el-input
            v-model="form.verifyCode"
            clearable
            placeholder="请输入短信验证码"
            :prefix-icon="useRenderIcon(Keyhole)"
          />
          <el-button :disabled="isDisabled" class="ml-2!" @click="sendCode">
            {{ text.length > 0 ? `${text}s` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="140">
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          clearable
          show-password
          placeholder="请设置登录密码"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          clearable
          show-password
          placeholder="请再次输入密码"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="240">
      <el-form-item prop="inviteCode">
        <el-input
          v-model="form.inviteCode"
          clearable
          placeholder="请输入邀请码（可选）"
          :prefix-icon="useRenderIcon(Key)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="280">
      <el-form-item class="agreement-row">
        <el-checkbox v-model="agree">我已阅读并同意</el-checkbox>
        <el-button link type="primary">{{ agreementLink }}</el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="320">
      <el-form-item>
        <el-button
          class="w-full"
          size="default"
          type="primary"
          :loading="loading"
          @click="onSubmit"
        >
          确认注册
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="360">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          返回
        </el-button>
      </el-form-item>
    </Motion>
  </el-form>
</template>

<style scoped>
.agreement-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.agreement-row .el-button {
  padding: 0;
}

.code-row {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.code-row .el-button {
  min-width: 110px;
}
</style>
